<?php

/**
 * Redis延迟队列
 * Class RedisQueue
 */
class RedisQueue
{
    /**
     * Redis延迟队列的接口地址
     * @var string
     */
    public static $redisDelayQueueAddress = 'http://127.0.0.1:9527/job';

    /**
     * 添加延迟任务
     * @method POST
     * @param string $topic     任务类型
     * @param string $id        任务唯一ID
     * @param int $delay        延迟时间
     * @param string $callback  回调URL
     * @param array $body      额外的数据内容
     * @return false|string
     */
    public static function add(string $topic, string $id, int $delay, string $callback, array $body):?string
    {
        $data = [
            'topic' => $topic,
            'id'    => $id,
            'delay'     => $delay,
            'callback'  => $callback,
            'body'      => $body,
        ];
        // 成功返回：{
        //  "success": 1,
        //  "message": "添加新任务成功",
        //  "data": null
        // }
        return ICurl::http_post(static::$redisDelayQueueAddress, $data, true);
    }

    /**
     * 查询任务信息
     * @param string $topic     任务类型
     * @param string $id        任务唯一ID
     * @return false|string
     */
    public static function get(string $topic, string $id):?string
    {
        $data = [
            'topic' => $topic,
            'id'    => $id
        ];
        // 成功返回：{
        //  "success": 1,
        //  "message": "添加新任务成功",
        //  "data": {
        //            "topic": "inform",
        //            "id": "08019413123",
        //            "delay": 1567135500,
        //            "body": {"example": true},
        //            "job_sign":"inform-08019413123"
        //          }
        // }
        return file_get_contents(static::$redisDelayQueueAddress . '?' . http_build_query($data));
    }

    /**
     * 删除延迟任务
     * @param string $topic     任务类型
     * @param string $id        任务唯一ID
     * @return array
     */
    public static function delete(string $topic, string $id):array
    {
        $data = [
            'topic' => $topic,
            'id'    => $id
        ];
        $cl = curl_init();
        curl_setopt($cl, CURLOPT_URL, static::$redisDelayQueueAddress . '?' . http_build_query($data));
        curl_setopt($cl, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($cl, CURLOPT_TIMEOUT, 6);
        // 结果
        $ret = [
            'response'  =>  curl_exec($cl),
            'status'    =>  curl_getinfo($cl)
        ];
        // 关闭curl
        is_resource($cl) and curl_close($cl);

        return $ret;
    }
}
